<?php
/**
 * Login.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-18
 * Time: 14:57
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Base;
use App\Tables;
use App\Tool\Crc32;
use Illuminate\Http\Request;

class Login extends Base
{
    public function login()
    {
        $v = \Validator::make(
            $this->request->post(),
            [
            'name' => 'required',
            'pass' => 'required',
            ],
            [
                'required' => ':attribute 不能为空',
            ],
            [
                'username' => '用户名',
                'pass' => '密码'
            ]
        );
        if($v->fails()) {
            return $this->responseFail($v->errors()->first());
        }
        $username = $this->request->post('name');
        $password = $this->request->post('pass');
        $remember = $this->request->post('remember');
        $find = Tables\Admin::where(['username' => $username])->first();
        if(empty($find)) {
            return $this->responseFail('用户名或密码错误!');
        }
        $checkMd5 = md5(md5($password).md5($find['salt']));
        if($checkMd5 !== $find['password']) {
            return $this->responseFail('用户名或密码错误!');
        }
        $uid = $find['id'];
        $token = Tables\Token::create($uid, $remember ? 86400*7 : 86400);
        if(!$token) {
            return $this->responseFail('生成令牌失效');
        }

        return $this->responseSuccess([
            'id' => $uid,
            'name' => $username,
            'token' => $token
        ]);
    }

    public function checkLogin()
    {
        $key = $this->request->post('key', '');
        $uid = $this->request->post('id', 0);
        if(empty($key) or $uid<=0) {
            return $this->responseFail();
        }

        $find = Tables\Token::where([
            'token' => $key,
            'token_crc32' => Crc32::get($key),
            'uid' => $uid
        ])->where('exp','>',time())->first();

        if(empty($find)) {
            return $this->responseFail();
        }
        if($find['exp'] < (strtotime(date('Ymd')) + 86400)) {
            $find->increment('exp', 86400);
        }
        return $this->responseSuccess();
    }

    public function out()
    {
        $ok = (bool) Tables\Token::where([
            'token' => self::getToken(),
            'token_crc32' => Crc32::get($this->getToken())
        ])->update([
            'exp' => 0,
            'update_time' => time()
        ]);
        return $ok ? $this->responseSuccess() : $this->responseFail();
    }

}